package com.maxatime.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class QrCodecController {

    @RequestMapping("/code")
    public void generateQrCode(HttpServletResponse response) throws WriterException, IOException {
        ServletOutputStream outputStream =response.getOutputStream();
        /*
        工厂类，用来给我们生成构造各种码（二维码，条形码）
        */

        MultiFormatWriter multiFormatWriter =new MultiFormatWriter();

        /*生成一个为矩阵*/
        /*二维码的内容 扫描二维码时会出现文字*/
        /*format生成二维码的类型 QR_CODE*/
        /*
        中间有你的头像
        可以是彩色 不是黑白色
        */
        String contents="i miss you SSB!";

        BarcodeFormat format=BarcodeFormat.QR_CODE;
        int width=400;
        int height=400;
        /*位矩阵*/
        Map<EncodeHintType, Object> hints=new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        hints.put(EncodeHintType.MARGIN,1);

        BitMatrix bitMatrix= multiFormatWriter.encode(contents,format,width,height,hints);

        MatrixToImageWriter.writeToStream(bitMatrix,"jpg",outputStream);
    }
}

